<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :file-list="flielist"
      :class="{disable:flielist.length===1}"
      :on-preview="preview"
      :on-remove="onRemove"
      :on-change="onChange"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showPwd" :percentage="propsd" :show-text="false" style="width:147px" />
    <el-dialog title="预览" :visible="showDialog" :close="showDialog=false">
      <el-row type="flex" justify="center">
        <img :src="imgUrl" alt="">
      </el-row>
    </el-dialog>
  </div>

</template>

<script>
// // 1. 引入库
var COS = require('cos-js-sdk-v5')
// 2. 创建实例
var cos = new COS({
  // 验证身份
  SecretId: 'AKIDwd5GAoCI7fwwf6pLbbMs9AxUlmX3JJ3Y',
  SecretKey: 'GG0UiiTyDCuLXUCfrpWx84lDPN5XjkX4'
})
export default {
  data() {
    return {
      showPwd: false,
      propsd: 0,
      flielist: [],
      imgUrl: '',
      showDialog: false
    }
  },
  methods: {
    preview(file) {
      // console.log(file.url)
      this.showDialog = true
      this.imgUrl = file.url
    },
    onRemove(file, fileList) {
      this.flielist = [...fileList]
    },
    onChange(file, fileList) {
      this.flielist = [...fileList]
    },
    beforeUpload(file) {
      // 校验大小
      const maxSize = 500 * 1024
      if (file.size > maxSize) {
        this.$message.error('上传文件大于500kB')
        return false
      }
      const whiteList = ['image/jpeg', 'image/png']
      if (!whiteList) {
        this.$message.error('目前只允许 jpeg / png 图片')
        return false
      }
    },
    upload(params) {
      console.log('开始上传')
      // console.log(12, params.file)
      this.showPwd = true
      cos.putObject({
        Bucket: 'hr-1306728208', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.propsd = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        if (!err) {
          console.log('异步上传成功')
          // console.log(data)
          this.flielist[0].status = 'success'
          this.flielist[0].url = 'http://' + data.Location
        }
        setTimeout(() => {
          this.showPwd = false
        }, 300)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.disable {
  ::v-deep .el-upload--picture-card{
    display:none;

  }
}

</style>
